import { App, Col, DatePicker, Form, Input, Row, Select } from 'antd'
import cs from 'classnames'
import dayjs from 'dayjs'
import localeData from 'dayjs/plugin/localeData'
import weekday from 'dayjs/plugin/weekday'
import lodash from 'lodash'
import { Dispatch, SetStateAction, useEffect, useRef, useState } from 'react'

import { Violation } from '@/api/interface'
import arrowNext from '@/assets/arrow-next.png'
import del from '@/assets/delete.png'
import scan from '@/assets/scan.png'
import OCRIdCard from '@/components/OCRIdCard'
import { getJson } from '@/utils/storage'

import styles from '../styles/index.module.less'

const { TextArea } = Input

dayjs.extend(weekday)
dayjs.extend(localeData)

const range = (start: number, end: number) => {
  const result = []
  for (let i = start; i < end; i++) {
    result.push(i)
  }
  return result
}

const dynamicFormat = (input) => {
  const inputArr = input
    .replace(/-/g, '')
    .replace(/[^0-9]+/, '')
    .split('')
  const split = [
    [0, 3],
    [3, 7],
    [7, 14],
    [14, 15],
  ]
  const result = []
  for (let i = 0; i < split.length; i++) {
    const text = inputArr.slice(split[i][0], split[i][1]).join('')
    if (text) {
      result.push(inputArr.slice(split[i][0], split[i][1]).join(''))
    }
  }
  return result.join('-')
}

const handleInputChangeEid = (event) => {
  const { value } = event.target
  event.target.value = dynamicFormat(value.trim())
}

interface Props {
  t: any
  lang: string
  cancel: () => void
  setSetup: Dispatch<SetStateAction<number>>
  violation: Partial<Violation>
  setViolation: Dispatch<SetStateAction<Partial<Violation>>>
  investigator: any
  setInvestigator: Dispatch<SetStateAction<any>>
}

function PersonalDetails({
  t,
  lang,
  cancel,
  setSetup,
  violation,
  setViolation,
  investigator,
  setInvestigator,
}: Props) {
  const { message } = App.useApp()
  const [form] = Form.useForm()
  const [ViolatorOrWitness, setViolatorOrWitness] = useState([])
  const [Users, setUsers] = useState([])
  const [Nationality, setNationality] = useState([])
  const [Violations, setViolations] = useState([])

  useEffect(() => {
    window.electron?.ipcRenderer.onStoreChange((value) => {
      const Users = JSON.parse(value.Users) || []
      const ViolatorOrWitness = JSON.parse(value.ViolatorOrWitness) || []
      const Nationality = JSON.parse(value.Nationality) || []
      const Violations = JSON.parse(value.Violations) || []
      setViolatorOrWitness(ViolatorOrWitness)
      setUsers(Users)
      setNationality(Nationality)
      setViolations(Violations)
    })
    const Users = getJson('Users') || []
    const ViolatorOrWitness = getJson('ViolatorOrWitness') || []
    const Nationality = getJson('Nationality') || []
    const Violations = getJson('Violations') || []
    setViolatorOrWitness(ViolatorOrWitness)
    setUsers(Users)
    setNationality(Nationality)
    setViolations(Violations)
  }, [])

  useEffect(() => {
    form.setFieldsValue({
      investigationDateValue: dayjs(),
      ...violation,
      details: violation.details.map((item) => {
        if (item.hiringDateValue) item.hiringDateValue = dayjs(item.hiringDateValue)
        return item
      }),
    })
  }, [])

  const FormLabel = ({ title, required = true }: { title: string; required?: boolean }) => {
    return (
      <span className={styles['form-item-label']}>
        {title}
        {required && <span className={styles['form-item-label-required']}>*</span>}
      </span>
    )
  }

  const disabledDate = (current: any) => {
    return current && current > dayjs().endOf('day')
  }

  const disabledDateTime = (current) => {
    const now = new Date()
    if (!current || !current.isSame(new Date(), 'day')) {
      return {}
    } else {
      const hour = now.getHours()
      const minute = now.getMinutes()
      const second = now.getSeconds()
      return {
        disabledHours: () => range(hour + 1, 24),
        disabledMinutes: () => {
          if (current && current.isSame(now, 'hour')) return range(minute + 1, 60)
          return []
        },
        disabledSeconds: () => {
          if (current && current.isSame(now, 'hour') && current.isSame(now, 'minute'))
            return range(second + 1, 60)
          return []
        },
      }
    }
  }

  const changeUser = (val, key) => {
    setInvestigator({ ...investigator, [key]: val })
  }

  const deleteDetail = (remove, name) => {
    remove(name)
    setViolation({ ...violation, eid: '' })
  }

  const [witnessesIndex, setWitnessesIndex] = useState(null)
  const [witnessesName, setWitnessesName] = useState(null)

  const OCRIdCardRef = useRef(null)
  const onOCRIdCard = (index, name) => {
    setWitnessesIndex(index)
    setWitnessesName(name)
    OCRIdCardRef.current.open()
  }

  const onData = (value) => {
    const nationality = lang === 'en-US' ? value.nationality : value.nationalityArabic
    const nationalityKey = Nationality.find(
      (item) => item.value[lang === 'en-US' ? 'en' : 'ar'] == nationality
    )?.key
    const details = form.getFieldValue('details')
    details[witnessesIndex] ?? (details[witnessesIndex] = {})
    details[witnessesIndex].name = lang === 'en-US' ? value.name : value.nameArabic
    details[witnessesIndex].eid = dynamicFormat(value.eid.replace(/-/g, '').trim())
    details[witnessesIndex].nationality = nationalityKey
    form.setFieldValue('details', details)
    // form.validateFields()
    const namePath = ['details', witnessesName, 'name']
    const eidPath = ['details', witnessesName, 'eid']
    const nationalityPath = ['details', witnessesName, 'nationality']
    const validateList = nationalityKey ? [namePath, eidPath, nationalityPath] : [namePath, eidPath]
    form.validateFields(validateList)
  }

  const onFinish = async (values: Partial<Violation>) => {
    // 获取所有 eid
    const allEid = values.details.map((detail) => detail.eid)

    // 查找重复的 eid
    const duplicates = allEid.reduce((acc, eid, index) => {
      if (allEid.indexOf(eid) !== index && !acc.includes(eid)) acc.push(eid)
      return acc
    }, [])

    if (duplicates.length > 0) return message.warning(t['form.personal.witnesses.emirates.warning'])

    const data = {
      ...violation,
      ...values,
      investigationDate: dayjs(values.investigationDateValue).format('HH:mm:ss DD/MM/YYYY'),
    }

    // 判断人员变化，清空签名
    const changesKey = []
    const signaturesKey = [
      'translator',
      'writer',
      'investigator',
      'investigator_2',
      'investigator_3',
    ]

    signaturesKey.forEach((key) => {
      if (values[key] !== violation[key]) changesKey.push(key)
    })

    let notEqualViolatorEids = []

    values.details.forEach((detail) => {
      for (const key in detail) {
        if (detail[key] === undefined) delete detail[key]
      }
    })

    if (!lodash.isEqual(values.details, violation.details)) {
      const diffObject = lodash.differenceWith(values.details, violation.details, lodash.isEqual)
      // console.log('不相等的对象', diffObject)
      notEqualViolatorEids = diffObject?.map((item) => item.eid)
    }

    data.details?.forEach((item) => {
      item.questions ?? (item.questions = [{ answer: '', question: '', attachment: [] }])
      if (item.hiringDateValue) {
        item.hiringDate = dayjs(item.hiringDateValue).format('DD/MM/YYYY')
      }
      if (item.nationality) {
        item.nationalityValue = Nationality.find((v) => v.key == item.nationality)?.value[
          lang === 'en-US' ? 'en' : 'ar'
        ]
      }
      if (notEqualViolatorEids.includes(item.eid)) {
        item.signature = ''
        item.signatures?.forEach((signature) => {
          signature.key === 'Witness/Violator' && (signature.value = '')
        })
      }
      item.signatures?.forEach((signature) => {
        if (changesKey.includes(signature.key)) signature.value = ''
      })
    })

    if (data.translator === '') data.translator = undefined

    setViolation(data)
    setSetup(2)
  }

  return (
    <div className={styles['form-personal']}>
      <Form layout="vertical" name="personal" form={form} onFinish={onFinish}>
        <Row gutter={24}>
          <Col md={12} xs={24}>
            <Form.Item label={<FormLabel title={t['form.personal.reference']} />}>
              <Form.Item
                name="refNumber"
                rules={[{ required: true, message: t['form.personal.reference.error'] }]}
              >
                <Select
                  options={Violations.map((item) => ({
                    value: item.refNumber,
                    label: item.refNumber,
                  }))}
                  allowClear
                  showSearch
                  optionFilterProp="label"
                  placeholder={t['form.personal.reference.placeholder']}
                  // notFoundContent={SelectEmpty}
                />
              </Form.Item>
            </Form.Item>
          </Col>
          <Col md={12} xs={24}>
            <Form.Item label={<FormLabel title={t['form.personal.date']} />}>
              <Form.Item
                name="investigationDateValue"
                rules={[{ required: true, message: t['form.personal.date.error'] }]}
              >
                <DatePicker
                  showTime
                  disabledDate={disabledDate}
                  disabledTime={disabledDateTime}
                  format={'HH:mm:ss DD/MM/YYYY'}
                  style={{ width: '100%' }}
                  className={styles['custom-date']}
                />
              </Form.Item>
            </Form.Item>
          </Col>
          <Col span={24}>
            <Form.Item label={<FormLabel title={t['form.personal.location']} />}>
              <Form.Item
                name="location"
                rules={[{ required: true, message: t['form.personal.location.error'] }]}
              >
                <Input
                  maxLength={500}
                  // placeholder={t['form.personal.location']}
                />
              </Form.Item>
            </Form.Item>
          </Col>
          <Col span={24}>
            <Form.Item label={<FormLabel title={t['form.personal.caseSummary']} />}>
              <Form.Item
                name="caseSummary"
                rules={[{ required: true, message: t['form.personal.caseSummary.error'] }]}
              >
                <TextArea
                  rows={4}
                  showCount
                  maxLength={5000}
                  // placeholder={t['form.personal.caseSummary']}
                />
              </Form.Item>
            </Form.Item>
          </Col>

          <div
            className={cs(styles['form-line'], 'mt-4 mb-8')}
            style={
              lang === 'en-US'
                ? { transform: 'translateX(12px)' }
                : { transform: 'translateX(-12px)' }
            }
          />

          <Col md={8} xs={24}>
            <Form.Item label={<FormLabel title={t['form.personal.writer']} />}>
              <Form.Item
                name="writer"
                rules={[{ required: true, message: t['form.personal.writer.error'] }]}
              >
                <Select
                  options={Users.map((item) => ({
                    value: item.id,
                    label: item.name,
                  }))}
                  allowClear
                  showSearch
                  optionFilterProp="label"
                  placeholder={t['form.personal.writer.placeholder']}
                  // notFoundContent={SelectEmpty}
                />
              </Form.Item>
            </Form.Item>
          </Col>
          <Col md={8} xs={24}>
            <Form.Item label={<FormLabel title={t['form.personal.translator']} required={false} />}>
              <Form.Item name="translator">
                <Input
                  maxLength={60}
                  //  placeholder={t['form.personal.translator']}
                />
              </Form.Item>
            </Form.Item>
          </Col>
          <Col md={8} xs={24}></Col>
          <Col md={8} xs={24}>
            <Form.Item label={<FormLabel title={t['form.personal.investigator']} />}>
              <Form.Item
                name="investigator"
                rules={[{ required: true, message: t['form.personal.investigator.error'] }]}
              >
                <Select
                  options={Users.map((item) => ({
                    value: item.id,
                    label: item.name,
                    disabled: Object.values(investigator).includes(item.id),
                  }))}
                  onChange={(val) => changeUser(val, 'one')}
                  allowClear
                  showSearch
                  optionFilterProp="label"
                  placeholder={t['form.personal.investigator.placeholder']}
                  // notFoundContent={SelectEmpty}
                />
              </Form.Item>
            </Form.Item>
          </Col>
          <Col md={8} xs={24}>
            <Form.Item
              label={<FormLabel title={t['form.personal.investigator2']} required={false} />}
            >
              <Form.Item name="investigator_2">
                <Select
                  options={Users.map((item) => ({
                    value: item.id,
                    label: item.name,
                    disabled: Object.values(investigator).includes(item.id),
                  }))}
                  onChange={(val) => changeUser(val, 'two')}
                  allowClear
                  showSearch
                  optionFilterProp="label"
                  placeholder={t['form.personal.investigator2.placeholder']}
                  // notFoundContent={SelectEmpty}
                />
              </Form.Item>
            </Form.Item>
          </Col>
          <Col md={8} xs={24}>
            <Form.Item
              label={<FormLabel title={t['form.personal.investigator3']} required={false} />}
            >
              <Form.Item name="investigator_3">
                <Select
                  options={Users.map((item) => ({
                    value: item.id,
                    label: item.name,
                    disabled: Object.values(investigator).includes(item.id),
                  }))}
                  onChange={(val) => changeUser(val, 'three')}
                  allowClear
                  showSearch
                  optionFilterProp="label"
                  placeholder={t['form.personal.investigator3.placeholder']}
                  // notFoundContent={SelectEmpty}
                />
              </Form.Item>
            </Form.Item>
          </Col>

          <div
            className={cs(styles['form-line'], 'mt-3 mb-5')}
            style={
              lang === 'en-US'
                ? { transform: 'translateX(12px)' }
                : { transform: 'translateX(-12px)' }
            }
          />

          <Col span={24} className={styles['form-personal-witnesses']}>
            <Form.List name="details">
              {(fields, { add, remove }) => (
                <>
                  {fields.map(({ key, name, ...restField }, index) => (
                    <Row key={key} gutter={24} className={styles['form-personal-witnesses-list']}>
                      <div className={styles['form-personal-witnesses-header']}>
                        <span className={styles['form-title-h4']}>
                          {t['form.personal.witnesses']} {index === 0 ? '' : index + 1}
                        </span>
                        <div className={styles['form-personal-witnesses-header-ri']}>
                          {/* <span
                            className={styles['form-personal-witnesses-ocr']}
                            onClick={() => onOCRIdCard(index, name)}
                          >
                            <img
                              src={scan}
                              className={styles['form-personal-witnesses-ocr-icon']}
                              alt="scan"
                            />
                            {t['form.personal.witnesses.ocr']}
                          </span> */}
                          {fields.length > 1 && (
                            <img
                              onClick={() => {
                                fields.length > 1 && deleteDetail(remove, name)
                              }}
                              src={del}
                              className={styles['form-personal-witnesses-del']}
                              alt="del"
                            />
                          )}
                        </div>
                      </div>
                      <Col md={8} xs={24}>
                        <Form.Item label={<FormLabel title={t['form.personal.witnesses.role']} />}>
                          <Form.Item
                            {...restField}
                            name={[name, 'role']}
                            rules={[
                              {
                                required: true,
                                message: t['form.personal.witnesses.role.error'],
                              },
                            ]}
                          >
                            <Select
                              options={ViolatorOrWitness.map((item) => ({
                                value: item.key,
                                label: item.value[lang === 'en-US' ? 'en' : 'ar'],
                              }))}
                              allowClear
                              showSearch
                              optionFilterProp="label"
                              placeholder={t['form.personal.witnesses.select.placeholder']}
                              // notFoundContent={SelectEmpty}
                            />
                          </Form.Item>
                        </Form.Item>
                      </Col>
                      <Col md={8} xs={24}>
                        <Form.Item label={<FormLabel title={t['form.personal.witnesses.name']} />}>
                          <Form.Item
                            {...restField}
                            name={[name, 'name']}
                            rules={[
                              {
                                required: true,
                                message: t['form.personal.witnesses.name.error'],
                              },
                            ]}
                          >
                            <Input
                              maxLength={500}
                              // placeholder={t['form.personal.witnesses.input.placeholder']}
                            />
                          </Form.Item>
                        </Form.Item>
                      </Col>
                      <Col md={8} xs={24}>
                        <Form.Item
                          label={<FormLabel title={t['form.personal.witnesses.emirates']} />}
                        >
                          <Form.Item
                            {...restField}
                            name={[name, 'eid']}
                            rules={[
                              {
                                required: true,
                                pattern: /^\d{3}-\d{4}-\d{7}-\d/,
                                message: t['form.personal.witnesses.emirates.error'],
                              },
                            ]}
                          >
                            <Input
                              maxLength={18}
                              placeholder={t['form.personal.witnesses.emirates.placeholder']}
                              onInput={handleInputChangeEid}
                            />
                          </Form.Item>
                        </Form.Item>
                      </Col>
                      <Col md={8} xs={24}>
                        <Form.Item
                          label={<FormLabel title={t['form.personal.witnesses.nationality']} />}
                        >
                          <Form.Item
                            {...restField}
                            name={[name, 'nationality']}
                            rules={[
                              {
                                required: true,
                                message: t['form.personal.witnesses.nationality.error'],
                              },
                            ]}
                          >
                            <Select
                              options={Nationality.map((item) => ({
                                value: item.key,
                                label: item.value[lang === 'en-US' ? 'en' : 'ar'],
                              }))}
                              allowClear
                              showSearch
                              optionFilterProp="label"
                              placeholder={t['form.personal.witnesses.select.placeholder']}
                              // notFoundContent={SelectEmpty}
                            />
                          </Form.Item>
                        </Form.Item>
                      </Col>
                      <Col md={8} xs={24}>
                        <Form.Item label={<FormLabel title={t['form.personal.witnesses.job']} />}>
                          <Form.Item
                            {...restField}
                            name={[name, 'job']}
                            rules={[
                              {
                                required: true,
                                message: t['form.personal.witnesses.job.error'],
                              },
                            ]}
                          >
                            <Input
                              maxLength={500}
                              // placeholder={t['form.personal.witnesses.input.placeholder']}
                            />
                          </Form.Item>
                        </Form.Item>
                      </Col>
                      <Col md={8} xs={24}>
                        <Form.Item
                          label={<FormLabel title={t['form.personal.witnesses.mobile']} />}
                        >
                          <Form.Item
                            {...restField}
                            name={[name, 'mobile']}
                            rules={[
                              {
                                required: true,
                                pattern: /^\d{10,15}$/,
                                message: t['form.personal.witnesses.mobile.error'],
                              },
                            ]}
                          >
                            <Input
                              maxLength={15}
                              placeholder={t['form.personal.witnesses.mobile.placeholder']}
                            />
                          </Form.Item>
                        </Form.Item>
                      </Col>
                      <Col md={8} xs={24}>
                        <Form.Item
                          label={<FormLabel title={t['form.personal.witnesses.address']} />}
                        >
                          <Form.Item
                            {...restField}
                            name={[name, 'address']}
                            rules={[
                              {
                                required: true,
                                message: t['form.personal.witnesses.address.error'],
                              },
                            ]}
                          >
                            <Input
                              maxLength={500}
                              // placeholder={t['form.personal.witnesses.input.placeholder']}
                            />
                          </Form.Item>
                        </Form.Item>
                      </Col>
                      <Col md={8} xs={24}>
                        <Form.Item
                          label={
                            <FormLabel
                              title={t['form.personal.witnesses.email']}
                              required={false}
                            />
                          }
                        >
                          <Form.Item
                            {...restField}
                            name={[name, 'email']}
                            rules={[
                              {
                                type: 'email',
                                message: t['form.personal.witnesses.email.error'],
                              },
                            ]}
                          >
                            <Input maxLength={500} />
                          </Form.Item>
                        </Form.Item>
                      </Col>
                      <Col md={8} xs={24}>
                        <Form.Item
                          label={
                            <FormLabel
                              title={t['form.personal.witnesses.hiringDate']}
                              required={false}
                            />
                          }
                        >
                          <Form.Item {...restField} name={[name, 'hiringDateValue']}>
                            <DatePicker
                              disabledDate={disabledDate}
                              format={'DD/MM/YYYY'}
                              style={{ width: '100%' }}
                              className={styles['custom-date']}
                            />
                          </Form.Item>
                        </Form.Item>
                      </Col>
                    </Row>
                  ))}
                  <Form.Item>
                    <span
                      onClick={() => add({ eid: '784-' })}
                      className={styles['form-personal-witnesses-add']}
                    >
                      {t['form.personal.witnesses.add']}
                    </span>
                  </Form.Item>
                </>
              )}
            </Form.List>
          </Col>
        </Row>
        <div className={styles['form-button']}>
          <div className={styles['form-button-pre']} onClick={() => cancel()}>
            <span className={styles['button-text']}>{t['form.button.cancel']}</span>
          </div>
          <div className={styles['form-button-next']} onClick={() => form.submit()}>
            <span className={styles['button-text']}>{t['form.button.next']}</span>
            <img src={arrowNext} className={styles['button-icon']} alt="next" />
          </div>
        </div>
      </Form>

      <OCRIdCard ref={OCRIdCardRef} onData={onData} />
    </div>
  )
}

export default PersonalDetails
